package com.mt.demo.service.impl;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.mt.demo.manager.MeetingRoomManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ScreenSharingService {
    @Autowired
    private SocketIOServer socketIOServer;

    @Autowired
    private MeetingRoomManager meetingRoomManager;

    // 开始屏幕共享
    public boolean startScreenSharing(String roomId, String userId, SocketIOClient client) {
        if (meetingRoomManager.setScreenSharingUser(roomId, userId)) {
            // 通知房间内其他用户有人开始共享屏幕
            for (SocketIOClient roomClient : meetingRoomManager.getRoomClients(roomId)) {
                if (!roomClient.getSessionId().equals(client.getSessionId())) {
                    roomClient.sendEvent("screenShareStarted", userId);
                }
            }
            return true;
        }
        return false;
    }

    // 停止屏幕共享
    public void stopScreenSharing(String roomId, String userId, SocketIOClient client) {
        String sharingUser = meetingRoomManager.getScreenSharingUser(roomId);
        if (sharingUser != null && sharingUser.equals(userId)) {
            meetingRoomManager.stopScreenSharing(roomId);
            // 通知房间内其他用户屏幕共享已停止
            for (SocketIOClient roomClient : meetingRoomManager.getRoomClients(roomId)) {
                if (!roomClient.getSessionId().equals(client.getSessionId())) {
                    roomClient.sendEvent("screenShareStopped", userId);
                }
            }
        }
    }

    // 获取当前共享屏幕的用户
    public String getScreenSharingUser(String roomId) {
        return meetingRoomManager.getScreenSharingUser(roomId);
    }

    // 检查用户是否可以开始屏幕共享
    public boolean canStartScreenSharing(String roomId) {
        return meetingRoomManager.getScreenSharingUser(roomId) == null;
    }

    // 清理用户的屏幕共享状态
    public void cleanupUserScreenSharing(String roomId, String userId) {
        String sharingUser = meetingRoomManager.getScreenSharingUser(roomId);
        if (sharingUser != null && sharingUser.equals(userId)) {
            meetingRoomManager.stopScreenSharing(roomId);
            // 通知房间内其他用户屏幕共享已停止
            for (SocketIOClient roomClient : meetingRoomManager.getRoomClients(roomId)) {
                roomClient.sendEvent("screenShareStopped", userId);
            }
        }
    }
}
